package org.example.thread4;

/**
 * 退出标志使线程正常退出
 *
 * @author wangMaoXiong
 * @version 1.0
 * @date 2022/12/27 15:53
 */
public class MyThread7 extends Thread {
    /**
     * 线程退出标识，true 标识退出、false 标识不退出
     */
    private boolean exitFlag = false;

    public void setExitFlag(boolean exitFlag) {
        this.exitFlag = exitFlag;
    }

    @Override
    public void run() {
        String name = Thread.currentThread().getName();
        try {
            System.out.println("[" + name + "] 运行开始.");
            int count = 10;
            for (int i = 0; i < count && !exitFlag && !isInterrupted(); i++) {
                System.out.println("[" + name + "] " + (i + 1));
                Thread.sleep(1000);
            }
            System.out.println("[" + name + "] 运行结束.");
        } catch (InterruptedException e) {
            System.out.println("[" + name + "] 中断异常退出，isInterrupted=" + Thread.currentThread().isInterrupted());
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        try {
            MyThread7 myThread = new MyThread7();
            myThread.start();
            int sleep = 2000;
            String name = Thread.currentThread().getName();
            System.out.println("[" + name + "] " + sleep + " 毫秒后停止子线程.");
            Thread.sleep(sleep);
            myThread.setExitFlag(true);
            System.out.println("[" + name + "] 运行结束.");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // [main] 2000 毫秒后停止子线程.
        // [Thread-0] 运行开始.
        // [Thread-0] 1
        // [Thread-0] 2
        // [main] 运行结束.
        // [Thread-0] 运行结束.
    }
}